package com.shop.cereshop.admin.alioss.service.impl;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.shop.cereshop.admin.alioss.service.TencentFileUploadService;
import com.shop.cereshop.commons.config.TXCOSConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Service("tencentfileuploadservice")
public class TencentFileUploadServiceImpl implements TencentFileUploadService {

    private final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    @Resource
    private TXCOSConfig tencentCOSConfig;


    @Override
    public String uploadFile(String filename, InputStream in, long size) throws Exception {
        log.info("tencent   filename {} size {}", filename, size);
        Objects.requireNonNull(filename);
        filename = filename.replaceAll(" ", "");
        String fileName = tencentCOSConfig.getFolderPrefix();
        String dateStr = format.format(new Date());
        String fileUrl = fileName + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "_" + filename);
//        InputStream inputStream = in;
        try {
            // 创建临时文件
            File tempFile = File.createTempFile("temp", null);
            // 将InputStream写入临时文件
            org.apache.commons.io.FileUtils.copyInputStreamToFile(in, tempFile);

            COSCredentials cred = new BasicCOSCredentials(tencentCOSConfig.getSecretId(), tencentCOSConfig.getSecretKey());
            // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
            ClientConfig clientConfig = new ClientConfig(new Region(tencentCOSConfig.getRegionName()));
            // 3 生成cos客户端
            COSClient cosclient = new COSClient(cred, clientConfig);
            // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
            PutObjectRequest putObjectRequest = new PutObjectRequest(tencentCOSConfig.getBucketName(), fileUrl, tempFile);
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            return tencentCOSConfig.getBaseUrl() + putObjectRequest.getKey();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
